package com.oro.dao.impl;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.log4j.Logger;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oro.dao.ClientiDao;
import com.oro.domain.Cliente;

public class HibernateClientiDaoSupport extends HibernateDaoSupport implements
		ClientiDao {

	
	
	
	Logger logger;

	
	@Override
	public void delete(Cliente cliente) {
		getHibernateTemplate().delete(cliente);
	}

	
	@Override
	public void delete(Long id) {
		getHibernateTemplate().delete(this.getCliente(id));
		
	}

	
	@Override
	public void deleteClienti() {
		getHibernateTemplate().deleteAll(getClienti());

	}

	
	@Override
	public Cliente getCliente(Long id) {
		return getHibernateTemplate().get(Cliente.class, id);
	}

	
	@Override
	public List<Cliente> getClienti() {
		return getHibernateTemplate().loadAll(Cliente.class);
	}

	@Override
	@SuppressWarnings("unchecked")
	
	public List<Cliente> getClientiByCognome(String cognome) {
		return getHibernateTemplate().find(
				"from Cliente as c where c.cognome = ?", cognome);
	}

	

	private Logger getLogger() {
		if (logger == null) {
			logger = Logger.getLogger(HibernateUserDaoSupport.class);
		}
		return logger;
	}
	
	@Override
	public int getNumeroClienti() {
		return DataAccessUtils.intResult(getHibernateTemplate().find(
				"select count(*) from Cliente"));
	}

	@PostConstruct
	public void postConstruct() {
		getLogger().info("HibernateClientiDaoSupport has been constructed.");
	}
	
	@PreDestroy
	public void preDestroy() {
		getLogger().info("HibernateClientiDaoSupport is being destroyed.");
	}

	
	@Override
	public void save(Cliente cliente) {
		this.getHibernateTemplate().saveOrUpdate(cliente);
	}

}
